package com.changanw.tienchin.channel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.changanw.tienchin.channel.domain.Channel;
import com.changanw.tienchin.channel.domain.vo.ChannelVo;
import com.changanw.tienchin.channel.mapper.ChannelMapper;
import com.changanw.tienchin.channel.service.IChannelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.changanw.tienchin.common.core.domain.AjaxResult;
import com.changanw.tienchin.common.core.domain.model.PieData;
import com.changanw.tienchin.common.exception.ServiceException;
import com.changanw.tienchin.common.utils.SecurityUtils;
import com.changanw.tienchin.common.utils.StringUtils;
import com.changanw.tienchin.common.utils.bean.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author changanw
 * @since 2023-11-15
 */
@Service
public class ChannelServiceImpl extends ServiceImpl<ChannelMapper, Channel> implements IChannelService {
  @Autowired
  ChannelMapper channelMapper;

  @Override
  public List<Channel> selectChannelList(ChannelVo channelVo) {
    return channelMapper.selectChannelList(channelVo);
  }

  @Override
  public AjaxResult addChannel(ChannelVo channelVo) {
    QueryWrapper<Channel> qw = new QueryWrapper<>();
    //查询当前名称并且是没有删除的
    qw.lambda().eq(Channel::getChannelName,channelVo.getChannelName()).eq(Channel::getDelFlag,0);
    Channel c = getOne(qw);
    if (c != null){
      //说明存在同名的渠道，并且没有删除
      return AjaxResult.error("存在同名渠道，添加失败");
    }
    Channel channel = new Channel();
    BeanUtils.copyProperties(channelVo,channel);
    channel.setCreateBy(SecurityUtils.getUsername());
    channel.setCreateTime(LocalDateTime.now());
    channel.setDelFlag(0);
    return save(channel) ? AjaxResult.success("添加成功") : AjaxResult.error("添加失败");
  }

  @Override
  public AjaxResult updateChannel(ChannelVo channelVo) {
    Channel channel = new Channel();
    BeanUtils.copyProperties(channelVo,channel);
    channel.setUpdateBy(SecurityUtils.getUsername());
    channel.setUpdateTime(LocalDateTime.now());
    //防止这三个属性被修改
    channel.setCreateTime(null);
    channel.setCreateBy(null);
    channel.setDelFlag(null);
    return updateById(channel) ? AjaxResult.success("更新成功"):AjaxResult.error("更新失败");
  }

  @Override
  public boolean deleteChannelByIds(Long[] channelIds) {
    UpdateWrapper<Channel> uw = new UpdateWrapper<>();
    uw.lambda().set(Channel::getDelFlag,1).in(Channel::getChannelId,channelIds);
    return update(uw);
  }

  @Override
  public String importUser(List<Channel> channelList, boolean updateSupport) {
    if (StringUtils.isNull(channelList) || channelList.size() == 0) {
      throw new ServiceException("导入用户数据不能为空！");
    }
    int successNum = 0;
    int failureNum = 0;
    StringBuilder successMsg = new StringBuilder();
    StringBuilder failureMsg = new StringBuilder();
    for (Channel channel : channelList) {
      try {
        // 验证当前渠渠道是否存在
        Channel channel1 = channelMapper.selectById(channel.getChannelId());
        if (StringUtils.isNull(channel1)) {
          //插入
          channel.setCreateBy(SecurityUtils.getUsername());
          channel.setCreateTime(LocalDateTime.now());
          channel.setDelFlag(0);
          save(channel);
          successNum++;
          successMsg.append("<br/>" + successNum + "、账号 " + channel.getChannelName() + " 导入成功");
        } else if (updateSupport) {
          //更新
          channel.setUpdateBy(SecurityUtils.getUsername());
          channel.setUpdateTime(LocalDateTime.now());
          updateById(channel);
          successNum++;
          successMsg.append("<br/>" + successNum + "、账号 " + channel.getChannelName() + " 更新成功");
        } else {
          failureNum++;
          failureMsg.append("<br/>" + failureNum + "、账号 " + channel.getChannelName() + " 已存在");
        }
      } catch (Exception e) {
        failureNum++;
        String msg = "<br/>" + failureNum + "、账号 " + channel.getChannelName() + " 导入失败：";
        failureMsg.append(msg + e.getMessage());
        log.error(msg, e);
      }
    }
    if (failureNum > 0) {
      failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
      throw new ServiceException(failureMsg.toString());
    } else {
      successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
    }
    return successMsg.toString();
  }

  @Override
  public AjaxResult channelAnalysis(ChannelVo channelVo) {
    //设置一个默认时间区间，默认查询前后一周的数据
    if (channelVo.getParams().get("beginTime") == null ||
            channelVo.getParams().get("endTime") == null){
      channelVo.getParams().put("beginTime",LocalDateTime.now().minusWeeks(1));
      channelVo.getParams().put("endTime",LocalDateTime.now().plusWeeks(1));
    }
    List<PieData> pieData = channelMapper.channelAnalysis(channelVo);

    return AjaxResult.success(pieData);
  }
}
